import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_constraint_box_widget/common_constraint_max_width_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_title_edit_with_underline_widget/typeof/common_title_edit_with_underline_typeof.dart';
import 'package:e_reception_flutter/net/net_api.dart';
import 'package:e_reception_flutter/net/server_api.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/check_in_record/record_history/export_excel/select_class_or_department.dart';
import 'package:e_reception_flutter/ui/company/company_detail/bean/department_or_class_list_response.dart';
import 'package:e_reception_flutter/ui/company/company_detail/class_or_department/class_or_department_page.dart';
import 'package:e_reception_flutter/ui/company/company_detail/class_or_department/class_or_department_viewmodel.dart';
import 'package:e_reception_flutter/ui/company/manager/edittext_widget.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_http_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:e_reception_flutter/vg_widgets/annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_base_callback.dart';
import 'package:vg_base/vg_sp_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_base/vg_time_util_lib.dart';
import 'package:vg_flutter_base_moudle/vg_moudle_widget_lib.dart';

import 'export_excel_success_page.dart';

class ExportExcelPage extends StatefulWidget {
  static Future<dynamic> navigatorPush(BuildContext context) {
    return RouterUtils.routeForFutureResult(
      context,
      ExportExcelPage(),
    );
  }

  @override
  State<StatefulWidget> createState() {
    return ExportExcelState();
  }
}

class ExportExcelState extends BaseState<ExportExcelPage> {
  static const int TYPE_STAFF = 0;
  static const int TYPE_PARENT = 1;
  static const int TYPE_STU = 2;

  ///选择类别
  int type = TYPE_STAFF;

  ///选择人员
  List<String> selectIds;
  String selectStr;

  ///开始日期
  DateTime startTime;
  String startTimeStr;

  ///结束日期
  DateTime endTime;
  String endTimeStr;

  ///接收邮箱
  String email;

  TextEditingController _controller, _emailController;

  ///是否可以提交
  ValueNotifier<bool> _enableCommit;

  RegExp exp = RegExp('^[a-zA-Z0-9_.-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+\$');

  String companyType = UserRepository.getInstance()?.userData?.companyInfo?.type;

  @override
  void initState() {
    super.initState();
    _enableCommit = ValueNotifier(false);
    _controller = TextEditingController(text: '');
    _controller.addListener(() {
      checkEnableCommit();
    });
    _emailController = TextEditingController(text: '');
    _emailController.addListener(() {
      String emailStr = _emailController?.text?.trim();
      if(_emailController?.text?.contains(" ")){
        emailStr =  _emailController?.text?.replaceAll(" ", "");
      }
      email = emailStr;
      checkEnableCommit();
    });
    _initGetEmail();
  }

  _initGetEmail() async{
   String setEmail = await SharePreferenceUtil.getString(UserRepository.getInstance().getCompanyId()+"email");
   if(setEmail!=null){
         _emailController?.text = setEmail;
       }
    //     .then((value){
    //   if(value!=null){
    //     _emailController?.text = value;
    //   }
    //   setState(() { });
    // });
  }

  @override
  Widget build(BuildContext context) {
    return CustomAnnotatedRegion(
      Scaffold(
        backgroundColor:
        ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
        body: Column(
          children: [
            VgTopBarWidget(
              title: '导出Excel',
            ),
            if (UserRepository.getInstance().isOrganization()) _selectWidget(),
            if (UserRepository.getInstance().isOrganization())
              _toSplitLineWidget(),
            _choosePeople(),
            _toSplitLineWidget(),
            timeRanges(),
            _toSplitLineWidget(),
            _emailWidget(),
            SizedBox(height: 50,),
            _confirmBtn()
          ],
        ),
      ),
      navigationBarColor:
      ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
    );
  }

  ///选择人员
  _choosePeople() {
    return Container(
      color: ThemeRepository.getInstance().getCardBgColor_21263C(),
      child: EditTextWidget(
        title: "选择人员",
        initContent: selectStr,
        controller: _controller,
        hintText: StringUtils.isEmpty(selectStr) ? "请选择" : selectStr,
        isShowGoIcon: true,
        onTap: (String editText, dynamic value) {
          if (type == TYPE_STAFF) {
            type = ClassOrDepartmentPage.TYPE_DEPARTMENT;
          } else {
            type = ClassOrDepartmentPage.TYPE_CLASS;
          }

          //员工进部门
          return SelectClassOrDepartmentPage.navigatorPush(
              context, type, selectIds);
        },
        onDecodeResult: (dynamic result) {
          if (result is! EditTextAndValue) {
            return null;
          }
          return result;
        },
        onChanged: (String editText, dynamic value) {
          if (value != null) {
            List<DepartmentOrClassListItemBean> selectBeans = value;
            List<String> selectIds = List();
            List<String> selectNames = List();

            selectBeans.forEach((element) {
              selectIds.add(element.getId());
              selectNames.add(element.getName());
            });
            this.selectIds = selectIds;
            selectStr = selectNames.join(",");
            checkEnableCommit();
          }
        },
      ),
    );
  }

  ///分割线
  Widget _toSplitLineWidget() {
    return Container(
      color: ThemeRepository.getInstance().getCardBgColor_21263C(),
      padding: const EdgeInsets.only(left: 15),
      height: 0.5,
      child: Container(
        color: ThemeRepository.getInstance().getLineColor_3A3F50(),
      ),
    );
  }

  ///时间范围
  timeRanges() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 15),
      color: ThemeRepository.getInstance().getCardBgColor_21263C(),
      child: Row(
        children: [
          Padding(
            padding: const EdgeInsets.only(right: 15),
            child: Text(
              '时间范围',
              style: TextStyle(color: Color(0xff808388), fontSize: 14),
            ),
          ),
          SizedBox(
            width: 2,
          ),
          Flexible(
            child: GestureDetector(
              behavior: HitTestBehavior.translucent,
              onTap: () {
                _startDatePicker();
              },
              child: Container(
                height: 50,
                alignment: Alignment.centerLeft,
                child: CommonConstraintMaxWidthWidget(
                  maxWidth: ScreenUtils.screenW(context) / 4,
                  child: _selectedText(
                      StringUtils.isEmpty(startTimeStr)
                          ? "开始日期"
                          : startTimeStr,
                      selected: !StringUtils.isEmpty(startTimeStr)),
                ),
              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 15.0),
            child: Text(
              '至',
              style: TextStyle(fontSize: 14, color: Colors.white),
            ),
          ),
          Flexible(
            child: GestureDetector(
              behavior: HitTestBehavior.translucent,
              onTap: () {
                _endDatePicker();
              },
              child: Container(
                height: 50,
                alignment: Alignment.center,
                child: CommonConstraintMaxWidthWidget(
                  maxWidth: ScreenUtils.screenW(context) / 4,
                  child: _selectedText(
                      StringUtils.isEmpty(endTimeStr) ? "结束日期" : endTimeStr,
                      selected: !StringUtils.isEmpty(endTimeStr)),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _selectedText(String text, {bool selected = false}) {
    return Text(
      text ?? '',
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
      style: TextStyle(
          color: selected ? Color(0xffd0e0f7) : Color(0xff5e687c),
          fontSize: 14),
    );
  }

  _emailWidget() {
    return Container(
      color: ThemeRepository.getInstance().getCardBgColor_21263C(),
      child: EditTextWidget(
        title: "接收邮箱",
        hintText: "请输入",
        controller: _emailController,
        readOnly: false,
        onDecodeResult: (dynamic result) {
          if (result is! EditTextAndValue) {
            return null;
          }
          return result;
        },
        onChanged: (String editText, dynamic value) {

        },
      ),
    );
  }

  _startDatePicker() {
    return DatePicker.showDatePicker(context,
        pickerTheme: DateTimePickerTheme(
            showTitle: true,
            backgroundColor:
            ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
            confirm: Text('确定',
                style: TextStyle(
                    color:
                    ThemeRepository.getInstance().getTextBFC2CC_BFC2CC())),
            cancel: Text('取消',
                style: TextStyle(
                    color:
                    ThemeRepository.getInstance().getTextBFC2CC_BFC2CC())),
            itemTextStyle: TextStyle(color: Colors.white)
          // backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
        ),
        minDateTime: DateTime.now().subtract(Duration(days: 365)),
        //起始日期
        maxDateTime:
        endTimeStr == null ? DateTime.now() : DateTime.parse(endTimeStr),
        //终止日期
        initialDateTime: startTime,
        //当前日期
        dateFormat: 'yyyy-MMMM-dd',
        //显示
        locale: DateTimePickerLocale.zh_cn,
        //语言 默认DateTimePickerLocale.en_us// 格式
        onClose: () => print("----- onClose -----"),
        onCancel: () => print('onCancel'),
        onConfirm: (dateTime, List<int> index) {
          //确定的时候
          setState(() {
            VgToolUtils.removeAllFocus(context);
            startTime = dateTime;
            startTimeStr = DateUtil.getDateStrByDateTime(startTime,
                format: DateFormat.YEAR_MONTH_DAY);
          });
          checkEnableCommit();
        });
  }

  _endDatePicker() {
    return DatePicker.showDatePicker(context,
        pickerTheme: DateTimePickerTheme(
          showTitle: true,
          backgroundColor:
          ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
          confirm: Text('确定',
              style: TextStyle(
                  color: ThemeRepository.getInstance().getTextBFC2CC_BFC2CC())),
          cancel: Text('取消',
              style: TextStyle(
                  color: ThemeRepository.getInstance().getTextBFC2CC_BFC2CC())),
          itemTextStyle: TextStyle(color: Colors.white),

          // backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
        ),
        minDateTime: startTimeStr == null
            ? DateTime.now().subtract(Duration(days: 365))
            : DateTime.parse(startTimeStr),
        //起始日期
        maxDateTime: DateTime.now(),
        //终止日期
        initialDateTime: endTime,
        //当前日期
        dateFormat: 'yyyy-MMMM-dd',
        //显示
        locale: DateTimePickerLocale.zh_cn,
        //语言 默认DateTimePickerLocale.en_us// 格式
        onClose: () => print("----- onClose -----"),
        onCancel: () => print('onCancel'),
        onConfirm: (dateTime, List<int> index) {
          VgToolUtils.removeAllFocus(context);
          //确定的时候
          if (dateTime.millisecondsSinceEpoch <
              startTime.millisecondsSinceEpoch) {
            VgToastUtils.toast(context, "结束日期不能早于开始日期");
            return;
          }
          setState(() {
            endTime = dateTime;
            endTimeStr = DateUtil.getDateStrByDateTime(endTime,
                format: DateFormat.YEAR_MONTH_DAY);
          });
          checkEnableCommit();
        });
  }

  _selectWidget() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 15),
      color: ThemeRepository.getInstance().getCardBgColor_21263C(),
      child: Row(
        children: [
          Padding(
            padding: const EdgeInsets.only(right: 15),
            child: Text(
              '选择类别',
              style: TextStyle(color: Color(0xff808388), fontSize: 14),
            ),
          ),
          SizedBox(
            width: 2,
          ),
          Flexible(child: _selectBtn(type == TYPE_STAFF, companyType=="S05"?'教工':'员工')),
          // Flexible(child: _selectBtn(type == TYPE_PARENT, '家长')),
          Flexible(child: _selectBtn(type == TYPE_STU, '学员')),
        ],
      ),
    );
  }

  _selectBtn(bool selected, String text) {
    return GestureDetector(
      onTap: () {
        int newType;
        switch (text) {
          case '员工':
            newType = TYPE_STAFF;
            break;
          case '教工':
            newType = TYPE_STAFF;
            break;
          // case '家长':
          //   newType = TYPE_PARENT;
          //   break;
          case '学员':
            newType = TYPE_STU;
            break;
        }
        if (type == TYPE_STAFF && newType != TYPE_STAFF) {
          selectIds = null;
          selectStr = null;
          _controller.text = null;
        }
        if (type != TYPE_STAFF && newType == TYPE_STAFF) {
          selectIds = null;
          selectStr = null;
          _controller.text = '';
        }
        type = newType;
        Future.delayed(Duration(milliseconds: 10))
            .then((value) => setState(() {}));
      },
      child: Container(
        height: 50,
        child: Row(
          children: [
            SizedBox(
                width: 20,
                height: 20,
                child: Image.asset(
                  selected ? 'images/select_w.png' : 'images/unselect_w.png',
                  width: 20,
                  height: 20,
                )),
            SizedBox(
              width: 8,
            ),
            Text(
              text,
              style: TextStyle(
                  color: selected ? Color(0xffd0e0f7) : Color(0xff5e687c),
                  fontSize: 14),
            )
          ],
        ),
      ),
    );
  }

  _confirmBtn() {
    return GestureDetector(
        onTap: () {
          if(!((email?.isNotEmpty ?? false) &&
              exp.hasMatch(email))){
                VgToastUtils.toast(context, "邮箱输入有误，请重新输入");
          }
          if (_enableCommit.value) {
            _exportExcelRequest();
          }
        },
        child: ValueListenableBuilder(
            valueListenable: _enableCommit,
            builder: (context, enableCommit, child) {
              return Container(
                width: double.infinity,
                height: 40,
                margin: EdgeInsets.only(left: 15, right: 15),
                child: Center(
                  child: Text(
                    '导出',
                    style: TextStyle(
                        color: enableCommit
                            ? Colors.white
                            : VgColors.INPUT_BG_COLOR,
                        fontWeight: FontWeight.w600),
                    textAlign: TextAlign.center,
                  ),
                ),
                decoration: BoxDecoration(
                  color: enableCommit
                      ? ThemeRepository.getInstance().getPrimaryColor_1890FF()
                      : ThemeRepository.getInstance()
                          .getTextEditHintColor_3A3F50(),
                  shape: BoxShape.rectangle,
                  borderRadius: BorderRadius.all(Radius.circular(24)),
                ),
              );
            }));
  }

  ///导出excel 请求
  _exportExcelRequest() {
    SharePreferenceUtil.putString(UserRepository.getInstance().getCompanyId()+"email", email);
    var params = {
      'authId': UserRepository.getInstance().authId,
      'beginTime': startTime.millisecondsSinceEpoch ~/ 1000,
      'endTime': endTime
              .add(Duration(hours: 23, minutes: 59, seconds: 59))
              .millisecondsSinceEpoch ~/
          1000,
      'chooseId': selectIds.join(","),
      'chooseName': selectStr,
      'type': type == TYPE_STAFF ? '04' : '02',
      'email': email
    };
    print(params.toString());
    loading(true, msg: "正在导出");
    VgHttpUtils.get(NetApi.EXPORT_EXCEL,
        params: params,
        callback: BaseCallback(onSuccess: (val) {
          loading(false);
          ExportExcelSuccessPage.navigatorPush(context, email);
        }, onError: (msg) {
          loading(false);
          toast(msg);
          print(msg);
        }));
  }

  ///是否可以提交
  void checkEnableCommit() {
    // RegExp exp = RegExp('^[a-zA-Z0-9_.-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+\$');
    _enableCommit.value = (((selectIds?.length) ?? 0) > 0) &&
        (selectStr?.isNotEmpty ?? false) &&
        (endTimeStr?.isNotEmpty ?? false) &&
        (email?.isNotEmpty ?? false) &&
        exp.hasMatch(email);
  }
}
